package com.lixingye.meowstar.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lixingye.meowstar.common.AppResult;
import com.lixingye.meowstar.common.ResultCode;
import com.lixingye.meowstar.dao.ArticleReplyMapper;
import com.lixingye.meowstar.exception.ApplicationException;
import com.lixingye.meowstar.model.ArticleReply;
import com.lixingye.meowstar.service.IArticleReplyService;
import com.lixingye.meowstar.service.IArticleService;
import com.lixingye.meowstar.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 猫大仙
 * @since 2025-01-14
 */
@Slf4j
@Service
public class ArticleReplyServiceImpl extends ServiceImpl<ArticleReplyMapper, ArticleReply> implements IArticleReplyService {
    @Autowired
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    private IArticleService articleService;
    @Override
    public void create(ArticleReply articleReply) {
        //校验
        if(articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null || StringUtil.isEmpty(articleReply.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //写入
        int insert = articleReplyMapper.insert(articleReply);
        if(insert!=1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新帖子表
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info(ResultCode.SUCCESS.toString()+", userID = "+articleReply.getId()+"postId = "+articleReply.getReplyUserId()+", 发帖成功");
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //非空校验
        if(articleId == null || articleId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        return articleReplies;
    }
}
